﻿using System;

namespace CryptoQrUtilities.Cryption
{
    /// <summary>
    /// An immutable implementation for a decryptor/encryptor that maintains many public keys for encrypting the AES key.
    /// </summary>
    internal class MultiKeyDencryptor : IMessageDencrypter
    {
        /// <summary>
        /// Create a new instance of <see cref="SingleKeyDencryptor"/> initializing .NET RSA container parameters.
        /// </summary>
        /// <param name="rsaProvider">The RSA provider to use with this dencryptor.</param>
        public MultiKeyDencryptor(IRsaProvider rsaProvider)
        {
            RsaProvider = rsaProvider;
        }

        #region IMessageDencrypter implementation

        public string DecryptMessage(QrMessage message)
        {
            // Verify we're using the correct type of message:
            var multiKeyMessage = message as MultiKeyQrMessage;

            if (multiKeyMessage == null)
            {
                throw new InvalidCastException("Should be a 'MultiKeyQrMessage' here.");
            }

            // Decrypt the message:
            var envelope = new CryptedEnvelope(message.MessageContents, true);
            var result = envelope.RetrieveEnvelopeContents(RsaProvider);

            return result;
        }

        #endregion

        /// <summary>
        /// Gets the RSA provider associated with this Dencryptor.
        /// </summary>
        public IRsaProvider RsaProvider { get; private set; }
    }
}
